const Encore = require('@symfony/webpack-encore');
const fs = require('fs');
const path = require('path');
const Dotenv = require('dotenv-webpack');
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    //.setManifestKeyPrefix('build/')
    .enableStimulusBridge('./assets/controllers.json')
    .splitEntryChunks()
    .configureSplitChunks(function(splitChunks) {
        splitChunks.minSize = 100000;
        splitChunks.maxSize = 300000;
        splitChunks.chunks = "all";
        splitChunks.automaticNameDelimiter = ".";
        splitChunks.minChunks = 2;
    })
    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())
    // .configureBabel((config) => {
    //     config.plugins.push('@babel/plugin-transform-runtime');
    // })

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = '3.30';
    })
    .enableVueLoader()
    .enableIntegrityHashes()
    .enableSassLoader()
    .enableLessLoader()
    // .enableStylusLoader()
    // .enablePostCssLoader()
    // .enableTypeScriptLoader()
    //.enableReactPreset()
    //.enableIntegrityHashes(Encore.isProduction())
    .autoProvidejQuery()
    .copyFiles({
        from: './assets/website/images',
        // optional target path, relative to the output dir
        // to: 'eduxpluswebsite/images/[path][name].[ext]',
        to: 'images/[path][name].[hash:8].[ext]',
        // only copy files matching this pattern
        //pattern: /\.(png|jpg|jpeg)$/
    })
;
Encore.addPlugin(new Dotenv());
const entryPoints = {};
function scanFolderForEntries(folderPath, prefix) {
    folderPath = fs.realpathSync(folderPath);
    const files = fs.readdirSync(folderPath);
    files.forEach(file => {
        const filePath = path.join(folderPath, file);
        const stat = fs.statSync(filePath);
        if (stat.isDirectory()) {
            // 如果是文件夹，则递归扫描子文件夹
            scanFolderForEntries(filePath);
        } else if (file.endsWith('.js')) {
            // 如果是 JavaScript 文件，则添加入口点
            const entryName = path.basename(file, '.js');
            entryPoints[prefix+"_"+entryName] = filePath;
        }
    });
}
scanFolderForEntries('./assets/website/pages',"website")
scanFolderForEntries('./assets/core/pages',"core")
scanFolderForEntries('./assets/edux/pages',"edux")
scanFolderForEntries('./assets/cms/pages',"cms")
scanFolderForEntries('./assets/h5/pages',"h5")

if (entryPoints) {
    for (var key in entryPoints) {
        Encore.addEntry(key, entryPoints[key]);
    }
}
const config = Encore.getWebpackConfig();
config.resolve.alias = {
    '~': path.resolve(__dirname, './'),
    '@': path.resolve(__dirname, './assets')
};

module.exports = config;
